#!/usr/bin/env python3
# coding: utf-8
"""
张威 2019-11-29
智能问答，对外提供接口Api,方便外部系统远程调用
"""
from sanic import  Sanic
from sanic.response import json,text
import asyncio
import py_eureka_client.eureka_client as eureka_client
import os
import sys
from chatbot_graph import  *

app = Sanic('__name__')
handler = None

#注册到eureka

def setEureka():
    server_host = "192.168.1.96"
    server_port = 8000
    eureka_client.init(eureka_server="http://192.168.3.187:8761/eureka",
                       app_name="qasysServer",
                       # 当前组件的主机名，可选参数，如果不填写会自动计算一个，如果服务和 eureka 服务器部署在同一台机器，请必须填写，否则会计算出 127.0.0.1
                       instance_host=server_host,
                       instance_port=server_port,
                       # 调用其他服务时的高可用策略，可选，默认为随机
                       ha_strategy=eureka_client.HA_STRATEGY_RANDOM)
setEureka()


@app.route("/" ,methods = ['GET','POST'])
async def index(request):
    questions = None;
    if request.method == 'GET':
        questions = request.args.get('q')
    else:
        questions = request.json.get('q')
    print('请求地址：{},方式{}，问题：{}'.format(request.ip,request.method, questions))
    answer = handler.chat_main(questions)
    dict = {'answers':answer}
    return json(dict,content_type = 'application/json;charset=utf-8')


if __name__ == "__main__":
    handler = ChatBotGraph()
    app.run(host='0.0.0.0', debug=False, port=8000, access_log=False) #dockcer 必须指定host='0.0.0.0'，否者映射不出来端口
    # app.run(debug=False, port=8001, access_log=True) #本地测试
